import { BrowserRouter, Routes, Route } from 'react-router-dom'
// 路由表
import changeRoutes from './page'

// 接口
import { routerType } from '../interface'

// 路由拦截器
import BeforeEach from './BeforeEach'

import React, { useEffect, useState } from 'react'
import { useSelector } from 'react-redux'

const Router = () => {

    // page: 路由表
    const [page, setPage] = useState(changeRoutes())

    // 二级菜单
    const menuList = useSelector((state:any) => state.menuList)

    useEffect(() => {
        setPage(changeRoutes(menuList))
    }, [menuList])

    // 渲染路由
    const renderRouter = (page: routerType[]) => {
        return page.map((item, idx) => {
            return <Route key={idx} path={item.path} element={<BeforeEach>{item.element}</BeforeEach>} >
                {
                    item.children && renderRouter(item.children)
                }
            </Route>
        })
    }


    return <BrowserRouter>
        <Routes>
            {
                renderRouter(page)
            }
        </Routes>
    </BrowserRouter>
}

export default Router